import React from 'react'
import api from '../../api'
import {Form, Row, Col, Button, Input} from 'antd'
import IconDom from '../../component/IconDom'
import MainUpload from './upload/MainList'
import SubUpload from './upload/SubList'
import DetailUpload from './upload/DetailList'
import ClaimUpload from './upload/ClaimList'
import AdditionalUpload from './upload/AdditionalList'
import ProcessBar from './ProcessBar'

const FormItem = Form.Item

class Service extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      step: 1,
      channelGoodsFaqDTOList: [],
      channelGoodsMediaDTOList: [],
      promotionData: {},
      mainList: [],
      subList: [],
      detailList: [],
      claimList: [],
      additionalList: [],
      lock: false

    }
    this.filterImgData = this.filterImgData.bind(this)
    this.removeImg = this.removeImg.bind(this)
    this.addQuestion = this.addQuestion.bind(this)
    this.deleteQuestion = this.deleteQuestion.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }
  componentDidMount () {
    let {promotionData} = this.props
    if (promotionData) {
      this.init(promotionData)
    }
  }
  componentWillReceiveProps (nextProps) {
    let {promotionData} = nextProps
    if (promotionData) {
      this.init(promotionData)
    }
  }
  getSrc (code) {
    let src = `/ajax/proxy/api/goods/file/downloadFile?fileUniqueCode=${code}`
    return src
  }
  init (promotionData) {
    let {lock} = this.state
    if (promotionData) {
      let {channelGoodsFaqDTOList, channelGoodsMediaDTOList} = promotionData
      this.setState({
        promotionData
      })
      this.setList(channelGoodsMediaDTOList)
      if (channelGoodsFaqDTOList && channelGoodsFaqDTOList.length > 0) {
        this.setState({
          channelGoodsFaqDTOList: promotionData.channelGoodsFaqDTOList
        })
      } else {
        !lock && this.queryInitFaq()
      }
    }
  }
  setList (channelGoodsMediaDTOList) {
    if (channelGoodsMediaDTOList) {
      let arr = []
      channelGoodsMediaDTOList.forEach(item => {
        let src = this.getSrc(item.fileCode)
        let mc = item.mediaCategory
        let listData = [{
          uid: item.fileCode,
          name: item.fileName,
          url: src
        }]
        mc === 1 && this.setState({mainList: listData})
        mc === 2 && this.setState({subList: listData})
        mc === 3 && this.setState({detailList: listData})
        mc === 4 && this.setState({claimList: listData})
        if (mc === 5) {
          arr = arr.concat(listData)
        }
      })
      this.setState({
        channelGoodsMediaDTOList,
        additionalList: arr
      })
    }
  }
  queryInitFaq () {
    T.ajax({
      url: api.queryInitFaq.path,
      loading: true
    }).then((res) => {
      if (res.code === 0) {
        this.setState({
          lock: true,
          channelGoodsFaqDTOList: res.data
        })
      }
    })
  }
  filterImgData (mediaCategory, imgListData) {
    let {channelGoodsMediaDTOList: list = []} = this.state
    let {promotionData} = this.props

    if (mediaCategory !== 5 && promotionData.channelGoodsMediaDTOList) {
      let arr = []
      list = list.map((item) => {
        // 替换
        arr.push(item.mediaCategory)
        if (item.mediaCategory === mediaCategory) {
          item = imgListData
        }
        return item
      })
      arr.forEach(item => {
        if (arr.indexOf(mediaCategory) === -1) {
          list.push(imgListData)
        }
      })
      list = list.filter(item => {
        return item.mediaCategory !== mediaCategory
      })
    }
    list.push(imgListData)
    this.setList(list)
    this.setState({
      channelGoodsMediaDTOList: list
    })
  }
  // 移除图片时候删掉对应发给后台的数据
  removeImg (mediaCategory, file, cb, additionalList) {
    let {channelGoodsMediaDTOList: list = []} = this.state
    if (mediaCategory === 5) {
      list = list.filter(item => {
        return item.fileCode !== file.uid
      })
      this.setState({additionalList})
    } else {
      list = list.filter(item => {
        return item.mediaCategory !== mediaCategory
      })
    }
    mediaCategory === 1 && this.setState({mainList: []})
    mediaCategory === 2 && this.setState({subList: []})
    mediaCategory === 3 && this.setState({detailList: []})
    mediaCategory === 4 && this.setState({claimList: []})

    this.setState({
      channelGoodsMediaDTOList: list
    }, () => {
      cb && cb()
    })
  }

  handleSubmit (e, btnType) {
    e.preventDefault()

    this.props.form.validateFields((err, values) => {
      if (err) return
      let {introduction} = values
      let data = {}
      let {channelGoodsFaqDTOList, channelGoodsMediaDTOList, promotionData} = this.state
      for (let i in values) {
        let index = i.replace(/(question)|(answer)/g, '')
        if (i.indexOf('answer') > -1) {
          channelGoodsFaqDTOList[index].answer = values[i]
        } else if (i.indexOf('question') > -1) {
          channelGoodsFaqDTOList[index].question = values[i]
        }
      }
      if (promotionData) {
        promotionData.introduction = introduction
        promotionData.channelGoodsFaqDTOList = channelGoodsFaqDTOList
        promotionData.channelGoodsMediaDTOList = channelGoodsMediaDTOList
        data = Object.assign({}, promotionData, {
          fromStep: 2,
          btnType
        })
      } else {
        data = Object.assign({}, data, promotionData, {
          fromStep: 2,
          btnType,
          introduction,
          channelGoodsFaqDTOList,
          channelGoodsMediaDTOList
        })
      }
      let flag = this.testData(channelGoodsMediaDTOList, channelGoodsFaqDTOList)
      if (!flag) return
      this.props.save(data)
    })
  }

  testData (imgList, qaList) {
    let flag = true
    if (imgList.length > 0 && qaList.length > 0) {
      let arr = []
      let allArr = [1, 2, 3, 4]
      imgList.forEach((item) => {
        arr.push(item.mediaCategory)
      })
      allArr.forEach(item => {
        if (arr.indexOf(item) === -1) {
          flag = false
          let msg = 'Please upload '
          item === 1 && (msg += 'main cover')
          item === 2 && (msg += 'sub cover')
          item === 3 && (msg += 'product features')
          item === 4 && (msg += 'claim process')
          T.showError(msg)
        }
      })
      qaList.forEach((item, index) => {
        // 只要有一个问题或答案为空则不通过。
        if (!item.answer || !item.question) {
          flag = false
          if (!item.answer) {
            T.showError(`Answer.${index + 1} is required`)
          }
          if (!item.question) {
            T.showError(`Question.${index + 1} is required`)
          }
        }
      })
    } else {
      flag = false
    }
    return flag
  }

  deleteQuestion (deleteIndex) {
    let {channelGoodsFaqDTOList} = this.state
    channelGoodsFaqDTOList = channelGoodsFaqDTOList.filter((item, index) => {
      return deleteIndex !== index
    })
    this.setState({channelGoodsFaqDTOList})
  }
  addQuestion () {
    let {channelGoodsFaqDTOList} = this.state
    channelGoodsFaqDTOList.push({
      question: '',
      answer: ''
    })
    this.setState({channelGoodsFaqDTOList})
  }
  render () {
    let {saleCompleteStaus, basicCompleteStaus, serviceCompleteStaus, tab} = this.props
    let {channelGoodsFaqDTOList = [], promotionData, mainList = [],
      subList = [],
      detailList = [],
      claimList = [],
      additionalList = []
    } = this.state
    let {getFieldDecorator} = this.props.form
    let formItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 18 }
    }
    let layout2 = {
      labelCol: {span: 2},
      wrapperCol: {span: 14}
    }
    return <div className='mt16 service-info'>
      <div className=''>

        {/* 进度条 */}
        <ProcessBar
          tab={tab}
          save={() => this.handleSubmit(null, 'save')}
          showPreview={this.props.showPreview}
          serviceCompleteStaus={serviceCompleteStaus}
          saleCompleteStaus={saleCompleteStaus}
          basicCompleteStaus={basicCompleteStaus} />

      </div>
      <div className='f16 strong process-sub-title'>
        Define Service
      </div>
      <div className='cover'>
        <Row className='upload-row'>
          <Col className='ant-form-item-required main-cover' span={3}>Main Cover：</Col>
          <Col span={6}>
            <MainUpload
              mainList={mainList}
              removeImg={this.removeImg}
              filterImgData={this.filterImgData}
              mediaCategory={1} />
          </Col>

          <Col className='ml20 wrap-col ant-form-item-required' span={2}>Sub Cover:</Col>
          <Col span={6} className='pl10'>
            <SubUpload
              subList={subList}
              removeImg={this.removeImg}
              filterImgData={this.filterImgData}
              mediaCategory={2} />
          </Col>

        </Row>
      </div>
      <Form onSubmit={this.handleSubmit}>
        <FormItem
          className='mt20'
          {...formItemLayout}
          label={'Introduction'}>
          {
            getFieldDecorator('introduction', {
              initialValue: promotionData.introduction || '',
              rules: [{required: true}]
            })(
              <Input.TextArea
                maxLength='500'
                autosize={{ minRows: 4, maxRows: 8 }}
                placeholder='Please Input'
                style={{width: '700px'}} />
              )
            }
        </FormItem>
        <div className='cover'>
          <Row className='upload-row'>
            <Col className='ant-form-item-required main-cover' span={3}>Product Features：</Col>
            <Col span={6}>
              <DetailUpload
                detailList={detailList}
                removeImg={this.removeImg}
                filterImgData={this.filterImgData}
                mediaCategory={3} />
            </Col>

            <Col
              className='ant-form-item-required ml20 wrap-col' span={2}>Claim Process:</Col>
            <Col span={6} className='pl10'>
              <ClaimUpload
                claimList={claimList}
                removeImg={this.removeImg}
                filterImgData={this.filterImgData}
                mediaCategory={4} />
            </Col>
          </Row>
        </div>
        <div className='mt20 questions'>
          <Row>
            <Col
              style={{'lineHeight': '40px'}}
              className='tar vm ant-form-item-required' span={3}>Common Q&A：</Col>
            <Col span={21}>
              {
                channelGoodsFaqDTOList.map((item, index) => {
                  return (
                    <div className='intro-item' key={index}>
                      <FormItem
                        {...layout2}
                        label={'Question.' + (index + 1)}>
                        {getFieldDecorator('question' + index, {
                          initialValue: item.question
                        })(
                          <Input
                            maxLength='200'
                            placeholder='default question' />)
                      }
                      </FormItem>
                      <FormItem
                        {...layout2}
                        label={'Answer'}>
                        {getFieldDecorator('answer' + index, {
                          initialValue: item.answer
                        })(
                          <Input.TextArea
                            maxLength='500'
                            autosize={{ minRows: 4, maxRows: 8 }}
                            placeholder='default answer' />)
                      }
                      </FormItem>
                      {
                        channelGoodsFaqDTOList.length > 1
                        ? <span
                          onClick={() => {
                            this.deleteQuestion(index)
                          }}
                          className='delete-icon'>
                          <IconDom code='icon-jianshao' />
                        </span> : ''
                      }
                      {
                        channelGoodsFaqDTOList.length - 1 === index
                        ? <span
                          onClick={this.addQuestion}
                          className={channelGoodsFaqDTOList.length === 1
                          ? 'plus-icon last-plus'
                          : 'plus-icon'}>
                          <IconDom code='icon-zengjia' />
                        </span>
                          : ''
                      }

                    </div>
                  )
                })
              }
            </Col>
          </Row>
        </div>
        <FormItem
          label={'Additional Info'}
          {...formItemLayout}>
          {getFieldDecorator('upload')(
            <AdditionalUpload
              additionalList={additionalList}
              removeImg={this.removeImg}
              filterImgData={this.filterImgData}
              mediaCategory={5} />
              )
            }
        </FormItem>
      </Form>
      <div className='next-btns'>
        <Button
          onClick={(e) => {
            this.handleSubmit(e, 'next')
          }}
          className='next-btn'>Next</Button>
      </div>
    </div>
  }
}
export default Form.create()(Service)
